'''
Created on 2013-7-23

@author: LJ
'''
import model
import random, time, os, hashlib
from owlparse import ogtxml

allfiles = ['Image', 'Audio', 'Video']

class tempfuns:
    @staticmethod
    def onlydate(datime):
        return datime.strftime("%b %d %Y")

def knowledgedbdata(stknow, knowid, info, uid):
    dat = {}
    for i in ogtxml.getAnnotationForms(stknow).keys():
        dat[i] = info.get(i)
    dat['knowid'] = knowid
    dat['creator'] = uid
    dat['date'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    return dat

def isUploadFile(stres):
    return ogtxml.resourceForms.get(stres, "text") == 'file'

def uploadFile(fileinfo):
    dire = "/static/upload/"
    filedir = os.curdir + dire
    fsplit = os.path.splitext( fileinfo.filename )
    fname = hashlib.new('md5', fsplit[0]+str(time.time())).hexdigest()[0:12] + fsplit[1]    
    fout = open(filedir+fname,'wb')
    fout.write(fileinfo.file.read())
    fout.close()
    return dire+fname

def resourcedbdata(stres, info, uid):
    dat = {}
    for i,j in ogtxml.resourceForm(stres).items():
        if i == 'resource' and j == 'file':
            pass
        else:
            dat[i] = info.get(stres+i)
    #resourceSpe = ['creator', 'date', 'ID', 'localPath']
    dat['creator'] = uid
    dat['date'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    if isUploadFile(stres):
        dat['localPath'] = uploadFile(info.get(stres+"resource"))
    rid = model.db.multiple_insert(stres, [dat])[0]
    return rid

def know2resdbdata(res, rid, know, kid):
    dat = {}
    dat['rid'] = rid
    dat['resource'] = res
    dat['knowledge'] = know
    dat['kid'] = kid
    model.db.multiple_insert('know2res', [dat])
    
def pointdbdata(info, uid):
    dat = {}
    va = ['resource', 'rid', 'value', 'comment']
    for i in va:
        dat[i] = info.get(i)
    dat['creator'] = uid
    dat['date'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    model.db.multiple_insert('res2point', [dat])
    return True

def isEmptydata(stres, info):
    dat = info.get(stres+"resource")
    if isUploadFile(stres):
        return dat.filename == '' or dat.filename == None
    else:
        return dat == '' or dat == None

def allResourcedbdata(kid, info, uid):
    for i in ogtxml.resourcesProperties(info.know):
        if isEmptydata(i[1], info):
            pass
        else:
            rid = resourcedbdata(i[1], info, uid)
            know2resdbdata(i[1], rid, info.know, kid)
            
def allResourcedbdataReuse(kid, info, uid):
    for i in ogtxml.resourcesProperties(info.know):
        strres = i[1]
        ids = info.get("change"+strres)
        if strres in allfiles:
            if ids != "0":
                for j in ids.split(","):
                    rid = int(j)
                    know2resdbdata(strres, rid, info.know, kid)
            if not isEmptydata(strres, info):
                rid = resourcedbdata(strres, info, uid)
                know2resdbdata(strres, rid, info.know, kid)
        else:
            if ids != "0":
                rid = int(ids)
                know2resdbdata(strres, rid, info.know, kid)
            else:
                if not isEmptydata(strres, info):
                    rid = resourcedbdata(strres, info, uid)
                    know2resdbdata(strres, rid, info.know, kid)


def getAllRes(stknow, kid):
    dat = {}
    for i in ogtxml.resourcesProList(stknow):
        re = model.db.select(i, where=" id in (select rid from know2res where resource=$i and knowledge=$stknow and kid=$kid) ", vars=locals())
        if bool(re):
            dat[i] = re
    return dat

def getMykonws(uid):
    dat = {}
    for i in ogtxml.knowledges2:
        re = model.db.select(i, where=" creator=$uid ", order="id DESC", limit=10, vars=locals())
        if bool(re):
            dat[i] = re
    return dat
        
def getMyPoints(uid):
    dat = {}
    re = model.db.select("res2point", where=" creator=$uid ", order="id DESC", limit=30, vars=locals())
    if not bool(re):
        return dat
    for i in re:
        if i.resource not in dat:
            dat[i.resource] = []
        dat[i.resource].append(i)
    return dat
    
    
def handleknows(knows):
    dat = {}
    for i in knows:
        key = i.knowledge
        if not dat.has_key(key):
            dat[key] = []
        dat[key].append(i.version)
    return dat

def handleknows_input(knows):
    dat = {}
    for i in knows:
        key = i.knowledge
        if not dat.has_key(key):
            dat[key] = []
        dat[key].append({"version":i.version, "name":i.name, "id":i.id})
    return dat

def select2list(sel):
    dat = []
    for i in sel:
        dat.append(i)
    return dat

def list2str(li):
    st = "( " + str(li[0])
    for i in li[1:]:
        st += ", " + str(i)
    st += " )"
    return st

def handleknowsdetail(ids):
    dat = {}
    for i,j in ids.items():
        st = "id in " + list2str(j)
        re = model.db.select(i, where= st, vars=locals())
        for k in re:
            key = i+ str(k['id'])
            dat[key] = k
    return dat

def addKnowsKey(knows):
    for i in knows:
        key = i.knowledge + str(i.version)
        i['idkey'] = key
    return knows


if __name__ == "__main__":
    print getAllRes("Process", 2)
#     re = model.db.select("Process", where=" id in ", vars=locals())




